package com.elite.h5mail.controller;

import com.elite.h5mail.bean.MailInitService;
import com.elite.h5mail.entity.DocumentIn;
import com.elite.h5mail.entity.DocumentOut;
import com.elite.h5mail.index.SendIndex;
import com.elite.h5mail.index.SendRepository;
import com.elite.h5mail.param.DocumentOutParam;
import com.elite.h5mail.service.IDocumentOutService;
import com.elite.h5mail.util.CleanPathUtil;
import com.elite.h5mail.util.ContentUtil;
import com.elite.h5mail.util.StringUtil;
import com.elite.h5mail.util.Util;
import net.sf.json.JSONObject;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class BaseController {
    private static final Logger log = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    public HttpServletRequest request;
    @Autowired
    public SendRepository sendRepository;
    @Autowired
    private IDocumentOutService documentOutService;

    public BaseController() {
    }

    protected MultipartHttpServletRequest getMultipartHttpServletRequest(HttpServletRequest request) {
        try {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            return mr;
        } catch (Exception var5) {
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest mr = resolver.resolveMultipart(request);
            return mr;
        }
    }

    public String getSendMsgid(String guid, String documentInGuid) {
        log.debug("getSendMsgid params: [guid: {}, documentin_guid: {}]", guid, documentInGuid);
        String returnStr = guid;
        if (documentInGuid != null && documentInGuid.length() > 0 && !documentInGuid.contains("undefined")) {
            DocumentIn documentin = new DocumentIn();
            documentin.setDocumentinGuid(documentInGuid);
            returnStr = this.documentOutService.queryDocumentInMsgid(documentin);
        }

        return returnStr.replace("\n", "");
    }

    private String getMail_sign(String staff_id, String epid, DataSource dataSource, String mail) {
        String signContent = "";
        if (MailInitService.embodyEpidMap.get(epid) != null && ((String) MailInitService.embodyEpidMap.get(epid)).length() > 0) {
            String getCustomerSql = MailInitService.selectSignSql.replaceAll("#C_BY", staff_id).replaceAll("#EMAIL", mail);

            getCustomerSql = StringUtil.mergeEpId(epid, getCustomerSql);
            List list = MailInitService.ebean.chaxun_sql(getCustomerSql, dataSource);
            StringWriter sw = new StringWriter();
            if (list != null && list.size() > 0) {
                Context context = new VelocityContext();
                int i = 0;

                while (true) {
                    if (i >= list.size()) {
                        Velocity.evaluate(context, sw, "velocity", (String) MailInitService.embodyEpidMap.get(epid));
                        break;
                    }

                    Map map = (Map) list.get(i);
                    Set set = map.keySet();
                    Iterator iter = set.iterator();

                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        log.debug("key:" + key);
                        String value = Util.filterForObject(map.get(key));
                        log.debug("value:" + value);
                        context.put(key, value);
                    }

                    ++i;
                }
            }

            String body = sw.toString();
            signContent = "<div class='eliteMailSign' style='padding 10px;'>" + body + "</div>";
        }

        return signContent;
    }

    public String getMailFrom(String rolegroup_id, String epid) {
        Map tempMap = (Map) MailInitService.mailEpidMap.get(epid);
        String mailfrom = "";
        if (tempMap != null) {
            mailfrom = (String) tempMap.get(rolegroup_id);
        }

        log.debug("mailfrom:" + mailfrom);
        if (mailfrom == null || mailfrom.equals("") || mailfrom.length() == 0) {
            log.debug("use defaultEmail");
            mailfrom = (String) MailInitService.defaultEmailMap.get(epid);
        }

        log.debug("mailfrom:" + mailfrom);
        return mailfrom;
    }

    public int doSaveEmlFile(String epid, DataSource dataSource, String type, String guid, String email_CC, String email_BCC, String email, String from, String subject, String content, String[] attachment, String emlFilePath, String[] Webattach, String ExpectedstartDate, String staff_id, String group_id, String documentin_guid, String Customer_guid, String mail_extendParam, String contentJson, String contentType, String indexflag) {
        int saveEmlResult = 0;
        int attachflag = 0;

        try {
            if ((attachment == null || attachment.length <= 0) && (Webattach == null || Webattach.length <= 0)) {
                attachflag = 0;
            } else {
                attachflag = 1;
            }

            Session session = Session.getInstance(new Properties());
            MimeMessage mimeMessage = new MimeMessage(session);
            Address[] cc = Util.getMailAddress(email_CC);
            if (cc != null) {
                mimeMessage.addRecipients(RecipientType.CC, cc);
            }

            Address[] bcc = Util.getMailAddress(email_BCC);
            if (bcc != null) {
                mimeMessage.addRecipients(RecipientType.BCC, bcc);
            }

            mimeMessage.addRecipients(RecipientType.TO, Util.getMailAddress(email));
            if (MailInitService.mailPersonalMap != null && MailInitService.mailPersonalMap.containsKey(from)) {
                Map tempMap = (Map) MailInitService.mailPersonalMap.get(from);
                log.debug("tempMap:" + tempMap);
                if (tempMap != null && tempMap.containsKey("personal") && tempMap.containsKey("charset")) {
                    String personal = (String) tempMap.get("personal");
                    String charset = (String) tempMap.get("charset");
                    if (personal != null && personal.length() > 0) {
                        mimeMessage.setFrom(new InternetAddress(from, personal, charset));
                    } else {
                        mimeMessage.setFrom(new InternetAddress(from));
                    }
                } else {
                    mimeMessage.setFrom(new InternetAddress(from));
                }
            } else {
                mimeMessage.setFrom(new InternetAddress(from));
            }

            mimeMessage.setSentDate(new Date());
            mimeMessage.setSubject(subject, "utf-8");
            String[] webAttachPaths = new String[Webattach != null ? Webattach.length : 0];
            DocumentOutParam documentOutParam = DocumentOutParam.builder().docTemplateId(new ArrayList()).build();
            if (Webattach != null && Webattach.length > 0) {
                AtomicInteger index = new AtomicInteger();
                Arrays.stream(Webattach).forEach((webAttach) -> {
                    String[] webAttachs = webAttach.split("\\|\\*:;;:\\*\\|");
                    if (webAttachs.length == 1) {
                        webAttachPaths[index.getAndIncrement()] = webAttachs[0];
                    } else {
                        webAttachPaths[index.getAndIncrement()] = webAttachs[1];
                        documentOutParam.getDocTemplateId().add(webAttachs[0]);
                    }

                });
            }

            MimeMessage msg = Util.createMessage(mimeMessage, content, attachment, webAttachPaths, contentJson, guid, type);
            if (type.equals("replyall") || type.equals("reply") || type.equals("forward")) {
                guid = Util.getGuid();
            }

            DocumentOut documentOut = new DocumentOut();
            documentOut.setDoctype(BigDecimal.valueOf(2L));
            if ("9".equals(contentType)) {
                documentOut.setStatus(BigDecimal.valueOf(9L));
            } else {
                documentOut.setStatus(BigDecimal.valueOf(0L));
            }

            documentOut.setTrialcount(BigDecimal.valueOf(0L));
            documentOut.setTrialcountlimit(BigDecimal.valueOf((long) MailInitService.trialCountLimit));
            documentOut.setComments(subject);
            documentOut.setSubject(subject);
            documentOut.setDocumentfrom(from);
            documentOut.setDocumentto(email);
            documentOut.setDocumentto2(email_CC);
            documentOut.setHandlebyId(staff_id);
            documentOut.setHandlegroupId(group_id);
            documentOut.setCustomerGuid(Customer_guid);
            documentOut.setStringfield1(documentin_guid);
            documentOut.setStringfield1("");
            documentOut.setStringfield2(type);
            documentOut.setCreatedBy(staff_id);
            documentOut.setCreatedDate(new Date());
            documentOut.setExpectedStartDate(ContentUtil.checkDate(ExpectedstartDate, ""));
            documentOut.setSubDoctype("");
            documentOut.setBlindcc("");
            documentOut.setAttachflag(Integer.valueOf(attachflag));
            String msgid = this.getSendMsgid(guid, documentin_guid);
            documentOut.setMsgid(msgid);
            emlFilePath = CleanPathUtil.cleanString(emlFilePath);
            log.debug("emlFilePath: {}", emlFilePath);

            try {
                FileOutputStream fos = new FileOutputStream(emlFilePath);
                Throwable var35 = null;

                try {
                    msg.writeTo(fos);
                } catch (Throwable var46) {
                    var35 = var46;
                    throw var46;
                } finally {
                    if (fos != null) {
                        if (var35 != null) {
                            try {
                                fos.close();
                            } catch (Throwable var45) {
                                var35.addSuppressed(var45);
                            }
                        } else {
                            fos.close();
                        }
                    }

                }
            } catch (Exception var48) {
                throw var48;
            }

            String uploadResult = Util.uploadFile(MailInitService.upload_url, emlFilePath, "/email/" + Util.FormatDateStr(new Date(), "yyyy-MM-dd"), "", "");
            log.debug("uploadResult:{}", uploadResult);
            Util.deleteFile(emlFilePath);
            JSONObject json = JSONObject.fromObject(uploadResult);
            String code = json.getString("code");
            log.debug("code : {}", code);
            String value = json.getString("value");
            log.debug("value : {}", value);
            documentOut.setDocumentPath(value);
            documentOut.setDocumentoutGuid(guid);
            documentOut.setIndexflag(indexflag);
            log.debug("这时候contentType-->" + contentType);
            if ("99".equals(contentType)) {
                saveEmlResult = this.documentOutService.updateDocumentOut(documentOut);
            } else {
                saveEmlResult = this.documentOutService.insertDocumentOut(documentOut);
            }

            log.debug("saveSmsResult : {}", saveEmlResult);
        } catch (Exception var49) {
            log.error("", var49);
        }

        return saveEmlResult;
    }

    public int saveMailToEml(String from, String epid, DataSource dataSource, String type, String guid, String email_CC, String email_BCC, String email, String subject, String content, String[] attachment, String[] webAttach, String sendtime, String staff_id, String rolegroup_id, String documentin_guid, String customer_guid, String mail_extendParam, String contentJson, String contentType) {
        if (!"reply".equals(type) && !"forward".equals(type)) {
            if (from == null || from.equals("") || from.length() == 0) {
                if ("AGENTMAIL".equals(MailInitService.mailFromType)) {
                    from = this.getMailFrom(staff_id, epid);
                } else {
                    from = this.getMailFrom(rolegroup_id, epid);
                }
            }
        } else if ("0".equals(MailInitService.replyMailFlag) && "AGENTMAIL".equals(MailInitService.mailFromType)) {
            from = this.getMailFrom(staff_id, epid);
        }

        log.debug("from:" + from);
        String emlPath = Util.getTempFilePath(MailInitService.emlTempPath, guid, guid + ".eml");
        log.debug("emlPath:" + emlPath);
        if (!"9".equals(contentType)) {
            if (!"reply".equals(type) && !"forward".equals(type)) {
                if (content == null || !content.contains("eliteMailSign")) {
                    content = content + this.getMail_sign(staff_id, epid, dataSource, from);
                }
            } else {
                Document doc = Jsoup.parse(content);
                doc.getElementById("sign").append(this.getMail_sign(staff_id, epid, dataSource, from));
                content = doc.toString();
                content = content.replace("sign", Util.getGuid());
                log.debug("reply_forward_content:" + content);
            }
        }

        String indexflag = "0";
        if (MailInitService.ebean.isSendIndexFlag()) {
            SendIndex sendIndex = new SendIndex();
            sendIndex.setContent(Util.delHTMLTag(content));
            sendIndex.setDocumentoutguid(guid);
            log.debug("sendRepository: {}", this.sendRepository);

            try {
                this.sendRepository.save(sendIndex);
                indexflag = "1";
            } catch (Exception var25) {
                log.error("e", var25);
                indexflag = "2";
            }
        }

        return this.doSaveEmlFile(epid, dataSource, type, guid, email_CC, email_BCC, email, from, subject, content, attachment, emlPath, webAttach, sendtime, staff_id, rolegroup_id, documentin_guid, customer_guid, mail_extendParam, contentJson, contentType, indexflag);
    }
}
